﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using AvalonDock;
using TheControllerRisk.Settings;
using RiskMan.DataClass.Models.NotBasModels;
using System.Windows.Threading;
using RiskMan.DataClass.Models.Level;
using System.Reflection;
using RiskMan.Views.Dialogs;

namespace RiskMan.Views.Level
{
    /// <summary>
    /// Логика взаимодействия для Level.xaml
    /// </summary>
    public partial class Level : DocumentContent
    {
        private MainWindow mainWindow;
        private DispatcherTimer _dsTimer = new DispatcherTimer();

        public Level()
        {
            mainWindow = RiskMan.MainWindow.StaticLevel;

            InitializeComponent();

            dtgdLevel.ItemsSource = mainWindow._dataProvider.LevelItems;
        }

        private void LevelLayout_Loaded(object sender, RoutedEventArgs e)
        {
            _dsTimer.Interval = TimeSpan.FromMilliseconds(1000);
            _dsTimer.Start();
            _dsTimer.Tick += new EventHandler(_dsTimer_Tick);
        }

        public void _dsTimer_Tick(Object sender, EventArgs args)
        {
            bool running = false;

            running = mainWindow.ConnectingOrDisconnecting(running);

            btnStart.IsEnabled = running;
            BtnStop.IsEnabled = running;

            if (running == true)
            {
                if (mainWindow._dataProvider.LevelItems.Count > 0)
                {
                    foreach (var item in mainWindow._dataProvider.LevelItems)
                    {
                        if (item.isRun == true)
                        {
                            LevelLogik logik = new LevelLogik(mainWindow, this);
                            logik.Start(item);
                        }
                    }

                }
            }
        }



        private void button3_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            if (dtgdLevel.SelectedItems.Count == 1)
            {
                int index = dtgdLevel.SelectedIndex + 1;
                //dtgdLevel.UnselectAll();
                try
                {
                    if (new DialogOkCancel("Вы действительно хотите скопировать строку " + index + "?", "Внимание").Result == MessageBoxResult.OK)
                    {
                        foreach (var item in mainWindow._dataProvider.LevelItems)
                        {
                            if (item.GuidLevelItem == ((LevelItem)(dtgdLevel.SelectedItem)).GuidLevelItem)
                            {
                                var tmp = (LevelItem)cfg.DeepClone(item);
                                tmp.isRun = false;
                                tmp.GuidLevelItem = Guid.NewGuid();
                                tmp.TradeList = new System.Collections.ObjectModel.ObservableCollection<TradesOpen>();
                                mainWindow._dataProvider.LevelItems.Add(tmp);
                            }
                        }

                    }
                }
                catch
                { }
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            bool flagChek = false;
            try
            {
                for (int i = 0; i < mainWindow._dataProvider.LevelItems.Count; i++)
                {
                    if (mainWindow._dataProvider.LevelItems[i].Check == true)
                    {
                        mainWindow._dataProvider.LevelItems.Remove(mainWindow._dataProvider.LevelItems[i]);

                        flagChek = true;
                        i--;
                    }
                }
            }
            catch
            {

            }

            if (flagChek == false)
                new DialogMessage("Не выбрано ни одного элемента для удаления", "Внимание!");
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_AddRow_Click(object sender, RoutedEventArgs e)
        {
            LevelItem item = new LevelItem();
            NewLevel nlvi = new NewLevel(item, mainWindow._dataProvider, false);
            nlvi.ShowDialog();

            if (item.Account != null)
                mainWindow._dataProvider.LevelItems.Add(item);

            //Update();
            cfg.SetLog("Добавлен новый уровень", mainWindow.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
        }

        private void DataGrid_Level_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void DataGrid_level_MouseUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < mainWindow._dataProvider.LevelItems.Count; i++)
            {
                mainWindow._dataProvider.LevelItems[i].Check = (sender as CheckBox).IsChecked.Value;
            }
            dtgdLevel.ItemsSource = mainWindow._dataProvider.LevelItems;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SettingLevelItems setiignLevelItems = new SettingLevelItems(Guid.NewGuid());
            setiignLevelItems.ShowDialog();

            button1.Focusable = false;
        }

        private void dtgdLevel_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            for (int i = 0; i < mainWindow._dataProvider.LevelItems.Count; i++)
            {
                if (((DataGrid)sender).SelectedIndex == i)
                    dtgdOrders.ItemsSource = mainWindow._dataProvider.LevelItems[i].TradeList;
            }
        }

        private void dtgdLevel_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            SettingLevelItems setiignLevelItems = new SettingLevelItems(((LevelItem)(((DataGrid)sender).SelectedItem)).GuidLevelItem);
            setiignLevelItems.ShowDialog();
        }

        private void dtgdOrders_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string classcode;
                for (int j = 0; j < mainWindow._dataProvider.LevelItems.Count; j++)
                {
                    if (mainWindow._dataProvider.LevelItems[j].Check == true)
                    {
                        foreach (var item in mainWindow._dataProvider.LevelItems[j].TradeList)
                        {
                            classcode = mainWindow._dataProvider.GetClasscode(mainWindow._dataProvider.LevelItems[j].Instrument);
                            if (item.OpenStatusOrder == cfg.Active)
                                mainWindow.Terminals.CancelOrder(item.OpenNumberOrder, mainWindow._dataProvider.LevelItems[j].Instrument, classcode, mainWindow._dataProvider.LevelItems[j].Account, mainWindow._dataProvider.LevelItems[j].ClientCode);
                            if (item.CloseStatusOrder == cfg.Active)
                                mainWindow.Terminals.CancelOrder(item.CloseNumberOrder, mainWindow._dataProvider.LevelItems[j].Instrument, classcode, mainWindow._dataProvider.LevelItems[j].Account, mainWindow._dataProvider.LevelItems[j].ClientCode);

                        }
                        mainWindow._dataProvider.LevelItems[j].TradeList.Clear();
                    }
                }


            }
            catch { }
            finally
            {
                for (int j = 0; j < mainWindow._dataProvider.LevelItems.Count; j++)
                {
                    if (mainWindow._dataProvider.LevelItems[j].Check == true)
                    {
                        mainWindow._dataProvider.LevelItems[j].TradeList.Clear();
                        mainWindow._dataProvider.LevelItems[j].CurNumberOfAttempt = 0;
                    }
                }
                //dtgdLevel.ItemsSource = mainWindow._dataProvider.LevelItems;
            }
        }

    }
}
